/*************************************************
* Title：TinyToolKit
* Author：Opportunity 
* Discribe：
* CreateTime：2020-04-09 16:23:30
* Version：1.0
* Modify Recoder：
*************************************************/

using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using TinyToolKit.Localization;  
using TinyToolKit;
using System.IO;

namespace TinyToolKitEditor
{
    [CustomEditor(typeof(TinyAutoTranslation))]
    public class TinyAutoTranslationInspector : EditorBase
    {
        private SerializedProperty key;
        private List<string> allKeys = new List<string>();  
        private List<string> autoFillKeys = new List<string>(); 
        private TinyAutoTranslation _target => target as TinyAutoTranslation;
        private TinyToolSettingAsset settingAsset;

        protected override void OnEnable()
        {
            base.OnEnable();
            key = serializedObject.FindProperty("key");
            
            if(settingAsset == null)
                settingAsset = Resources.Load<TinyToolSettingAsset>("TinyToolSetting");
            ParseSettingAsset();
        }

        private void ParseSettingAsset()
        {
            if (settingAsset && settingAsset.localizationPaths.Length > 0)
                LoadLocalizationFile(settingAsset.localizationPaths[0].path);
        }

        public override void OnInspectorGUI()
        {
            base.OnInspectorGUI();

            if (settingAsset == null) return;

            if (settingAsset.localizationPathType == LocalizationPathType.Resources)
                EditorGUILayout.HelpBox("请将配置表放在 Resources 文件中", MessageType.Info);
            else if (settingAsset.localizationPathType == LocalizationPathType.StreamingAssets)
                EditorGUILayout.HelpBox("请将配置表放在 StreamingAssets 文件中", MessageType.Info);
            else if (settingAsset.localizationPathType == LocalizationPathType.Custom)
                EditorGUILayout.HelpBox("自定义模式不支持自动填充", MessageType.Info);
            
            serializedObject.Update();
            EditorGUILayout.LabelField("Lan",Enum.GetName(typeof(Language),_target.curLan));
            EditorGUILayout.PropertyField(key);
            if (EditorApplication.isPlaying == false)
                AutoComplete();
            serializedObject.ApplyModifiedProperties();
        }

        private void AutoComplete()
        {
            if (string.IsNullOrEmpty(_target.key)) return;

            autoFillKeys.Clear();
            foreach (string key in allKeys)
            {
                string tempKey = key.ToLower();
                string targetKey = _target.key.ToLower();
                if (tempKey.Contains(targetKey)) 
                    autoFillKeys.Add(key);
            }

            GUILayout.BeginHorizontal("box");
            GUILayout.Label(string.Format("Auto Fill ({0})", autoFillKeys.Count), EditorStyles.boldLabel, GUILayout.ExpandWidth(true));
            GUILayout.EndHorizontal();

            bool isClear = false;
            foreach (string key in autoFillKeys)
            {
                if (GUILayout.Button(key))
                {
                    _target.key = key;
                    GUI.FocusControl(null);
                    isClear = true;
                }
            }
            if (isClear)
                autoFillKeys.Clear();
        }

        public void LoadLocalizationFile(string filePath)
        {
            if (settingAsset != null)
            {
                LocalizationPathType pathType = settingAsset.localizationPathType;   

                string jsonMsg = string.Empty;
                switch (pathType)
                {
                    case LocalizationPathType.Resources:
                        filePath = TinyUtility.Path.GetPathWithoutExtension(filePath);
                        TextAsset textAsset = Resources.Load<TextAsset>(filePath);
                        if (textAsset != null)
                            jsonMsg = textAsset.text;
                        break;
                    case LocalizationPathType.StreamingAssets:
                        filePath = TinyUtility.Path.GetStreamingAssetsPath() + filePath;
                        int index = -1;
                        index = filePath.LastIndexOf(".");
                        if (index < 0)
                            filePath = TinyUtility.Path.GetPathWithoutExtension(filePath) + ".json";
                        if (File.Exists(filePath))
                            jsonMsg = File.ReadAllText(filePath);
                        break;
                }

                if (string.IsNullOrEmpty(jsonMsg) == false)
                    ParseTranslationJson(jsonMsg);
            }
        }

        private void ParseTranslationJson(string jsonMsg)
        {
            Translation translation = JsonUtility.FromJson<Translation>(jsonMsg);
            if (translation == null) return;
            for (int i = 0; i < translation.TransItems.Count; i++)
            {
                TranslationItem item = translation.TransItems[i];
                string key = item.Category + "." + item.Key;
                allKeys.Add(key);
            }
        }
    }
}
